package leetcode;

import java.util.HashMap;

public class IsomorphicStrings {

	public static void main(String[] args) {
		String string = "egg";
		String t = "add";
		IsomorphicStrings object = new IsomorphicStrings();
		System.out.println(object.isIsomorphic(string, t));
	}
	
	//最好理解的方法，建立两个hashMap分别表示s到t的映射和t到s的映射
	//有点类似 Word Pattern
	public boolean isIsomorphic(String s, String t) {
		if(s == null || t == null || s.length() <= 0 || t.length() <= 0){
            return s.equals(t);
        }
		HashMap<Character, Character> map = new HashMap<>();
		HashMap<Character, Character> reMap = new HashMap<>();
		//每一个字符与一个字符有对应关系，如果不一样，那么就说明不是对应的
		char[] sChars = s.toCharArray();
		char[] tChars = t.toCharArray();
		map.put(sChars[0], tChars[0]);
		reMap.put(tChars[0], sChars[0]);
		for (int i = 0; i < tChars.length - 1; i++) {
			if(map.get(sChars[i]) == null || map.get(sChars[i]) != tChars[i]){
				System.out.println("111");
				return false;
			}
			if(reMap.get(tChars[i]) == null || reMap.get(tChars[i]) != sChars[i]){
				System.out.println("2222");
                 return false;
            }
			//为了防止新加入的覆盖已有的，比如s = "ab", t= "aa"
			if(map.containsKey(sChars[i + 1]) && map.get(sChars[i + 1]) != tChars[i + 1]){
                return false;
            }
            if(reMap.containsKey(tChars[i + 1]) && reMap.get(tChars[i + 1]) != sChars[i + 1]){
                return false;
            }
			map.put(sChars[i + 1], tChars[i + 1]);
			reMap.put(tChars[i + 1], sChars[i + 1]);
		}
		return true;
	}
}
